package net.borlis.server.outer;

import net.borlis.server.properties.ServerProperties;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletException;
import java.io.File;

/**
 * Created by borlis on 26.12.2014.
 */
public final class OuterServer {
    private static final String WEB_APP_DIRECTORY = "src/main/webapp/WEB-INF/";
    private Tomcat tomcat;
    private static volatile OuterServer instance;

    private OuterServer() {
    }

    public static synchronized OuterServer getInstance() {
        if (instance == null) {
            instance = new OuterServer();
        }
        return instance;
    }

    public synchronized Tomcat getServer(ServerProperties serverProperties) {
        if (instance == null) {
            instance = new OuterServer();
        }
        if (tomcat == null) {
            init(serverProperties.getPort());
        }
        return tomcat;
    }

    public void start() {
        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }

    private void init(String port) {
        tomcat = new Tomcat();
        tomcat.setPort(Integer.valueOf(port));
        try {
            tomcat.addWebapp("/", new File(WEB_APP_DIRECTORY).getAbsolutePath());
        } catch (ServletException e) {
            e.printStackTrace();
        }
        System.out.println("configuring app with basedir: " +
                new File("./" + WEB_APP_DIRECTORY).getAbsolutePath());
    }
}
